package edu.zhang.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.zhang.dao.LoginDAO;
import edu.zhang.dao.AdminDAO;
import edu.zhang.po.Admin;

@WebServlet("/Back/LoginController")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private LoginDAO loginDAO = new LoginDAO();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		Admin admin = loginDAO.login(account, password);

		request.getSession().setAttribute("admin", admin);

		if (admin != null) {
			String nologin = request.getParameter("nologin");
			if (nologin != null) {
				Cookie accountCookie = new Cookie("account", admin.getAccount());
				Cookie passwordCookie = new Cookie("password", admin.getPassword());
				accountCookie.setMaxAge(60 * 60 * 24 * 7);
				passwordCookie.setMaxAge(60 * 60 * 24 * 7);
				response.addCookie(accountCookie);
				response.addCookie(passwordCookie);
			}
			request.getRequestDispatcher("index.jsp").forward(request, response);
		} else {
			response.sendRedirect("/Ordering/Back/login.html");
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
